package com.xsq.page;

import android.media.AudioAttributes;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.xsq.BaseApplication;
import com.xsq.Constants;
import com.xsq.R;
import com.xsq.data.CardInfo;
import com.xsq.utils.HttpUtil;
import com.xsq.utils.StatusUtils;
import com.xsq.view.easykeyboard.SystemKeyboardForTextView;
import com.xsq.view.easykeyboard.action.KeyBoardForTextViewActionListener;

import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.util.LogUtil;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import Lib.FWReader.S8.function_S8;

@ContentView(R.layout.fragment_main_consume)
public class MainConsumeAuto extends BaseFragment implements View.OnClickListener {

    private View rootView;
    @ViewInject(R.id.keyboard)
    SystemKeyboardForTextView keyboard;
    @ViewInject(R.id.time)
    TextView time;
    @ViewInject(R.id.layout_card)
    RelativeLayout layoutCard;
    @ViewInject(R.id.read_card_status)
    TextView textReadStatus;
    @ViewInject(R.id.text_name)
    TextView textName;
    @ViewInject(R.id.edit_card)
    EditText editCard;
    @ViewInject(R.id.text_yue)
    TextView textYue;
    @ViewInject(R.id.edit_money)
    TextView editMoney;
    @ViewInject(R.id.btn_submit)
    Button submit;

    private Gson gson;
    private CardInfo cardInfo;
    /*** 是否正在读卡 ***/
    private boolean isReadingCard;
    /*** 读卡 ***/
    private function_S8 call_contactLess;
    private int result = 0;
    private int hdev = 1;
    private char[] pModVer = new char[512];
    private char[] pSnrM1 = new char[255];
    /*** 定时读卡 ***/
    private Timer mTimer = null;
    private TimerTask mTimerTask = null;
    private static int count = 0;
    private boolean isPause = false;
    private boolean isStop = true;
    private static int period = 500;  //1s
    /*** 音频播放 ***/
    private HashMap<Integer, Integer> soundMap;
    private SoundPool soundpool;

    public static MainConsumeAuto newInstance() {
        MainConsumeAuto f = new MainConsumeAuto();
        Bundle args = new Bundle();
        //args.putInt("index", index);
        f.setArguments(args);
        return f;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        gson = new Gson();
        call_contactLess = new function_S8(getActivity());
        call_contactLess.SetTransPara(0x20, 1137,41234);
        //连接端口
        do {
            hdev = call_contactLess.fw_init_ex(2, null, 0);
            if(hdev != -1) {
                result = call_contactLess.fw_getver(hdev, pModVer);
                if(result != 0){
                    call_contactLess.fw_exit(hdev);
                    hdev = -1;
                }
            }
        }while(hdev == -1);
        AudioAttributes attr = new AudioAttributes.Builder()           //设置音效相关属性
                .setUsage(AudioAttributes.USAGE_GAME)                 // 设置音效使用场景
                .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)  // 设置音效的类型
                .build();
        soundpool = new SoundPool.Builder()           // 创建SoundPool对象
                .setAudioAttributes(attr) // 设置音效池的属性
                .setMaxStreams(10) // 设置最多可容纳10个音频流，
                .build();
        //创建一个HashMap对象,将要播放的音频流保存到HashMap对象中
        soundMap = new HashMap<>();
        soundMap.put(0, soundpool.load(getActivity(), R.raw.beep, 1));
        soundMap.put(1, soundpool.load(getActivity(), R.raw.success, 1));
        soundMap.put(2, soundpool.load(getActivity(), R.raw.fail_not_enough, 1));
        soundMap.put(3, soundpool.load(getActivity(), R.raw.fail_type_forbid, 1));
        soundMap.put(4, soundpool.load(getActivity(), R.raw.fail_exceed, 1));
        soundMap.put(5, soundpool.load(getActivity(), R.raw.fail, 1));
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if(rootView == null) {
            rootView = x.view().inject(this, inflater, container);
        }
        if(BaseApplication.getInstance().getPriceType() == PriceType.Auto) {
            submit.setEnabled(false);
            editMoney.setText(BaseApplication.getInstance().getAutoPrice());
        }else {
            submit.setEnabled(true);
            keyboard.setOnKeyboardActionListener(boardForTextViewActionListener);
        }
        layoutCard.setOnClickListener(this);
        submit.setOnClickListener(this);
        editCard.addTextChangedListener(textWatcher);
        //editCard.requestFocus();
        editCard.setInputType(InputType.TYPE_NULL);
        return rootView;
    }

    /**
     * 交易金额与自定义键盘的监听
     */
    private KeyBoardForTextViewActionListener boardForTextViewActionListener = new KeyBoardForTextViewActionListener() {
        @Override
        public void onComplete() {
        }
        @Override
        public void onTextChange(String content) {
            editMoney.setText(content);
            ((MainActivity)getActivity()).notifyUserScreenOrderMoney(content);
        }
        @Override
        public void onClear(String content) {
            editMoney.setText(content);
            ((MainActivity)getActivity()).notifyUserScreenOrderMoney(content);
        }
        @Override
        public void onClearAll() {
        }
    };
    /**
     * 编号位置的EditText监听（针对二维码扫描输入）
     */
    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
        @Override
        public void afterTextChanged(Editable s) {
            String sn = s.toString();
            LogUtil.e("---接收到条码扫描---" + sn);
            if (!TextUtils.isEmpty(sn) && sn.length() >= 8) {
                sn = sn.substring(0, 8);
                LogUtil.i("---接收到条码扫描2: " + sn);
                //if (!sn.equals(((MainActivity)getActivity()).cardNo)) {
                    ((MainActivity)getActivity()).cardNo = sn;
                    fetchCardInfo(((MainActivity)getActivity()).cardNo);
                //}
                Message msg = new Message();
                msg.what = 1;
                msg.obj = ((MainActivity)getActivity()).cardNo;
                mHandler.sendMessage(msg);
            }
        }
    };

    @Override
    public void onResume() {
        super.onResume();
        new ClockThread().start();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopTimer();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_submit:
                if(TextUtils.isEmpty(((MainActivity)getActivity()).cardNo)) {
                    showDialog("没有卡号", 1000);
                    ((MainActivity)getActivity()).notifyUserScreenDialog("没有卡号", 1000);
                    return;
                }
                String money = editMoney.getText().toString();
                if(TextUtils.isEmpty(money)) {
                    showDialog("请输入交易金额", 1000);
                    ((MainActivity)getActivity()).notifyUserScreenDialog("请输入交易金额", 1000);
                    return;
                }
                BigDecimal orderMoney = new BigDecimal(money);
                if(orderMoney.doubleValue() <= 0) {
                    showDialog("请输入交易金额", 1000);
                    ((MainActivity)getActivity()).notifyUserScreenDialog("请输入交易金额", 1000);
                    return;
                }
                if(orderMoney.doubleValue() > 10000) {
                    showDialog("交易金额不能大于10000", 1000);
                    ((MainActivity)getActivity()).notifyUserScreenDialog("交易金额不能大于10000", 1000);
                    return;
                }
                BigDecimal p = new BigDecimal(100);
                BigDecimal orderAmount = orderMoney.multiply(p);
                reportConsumeRecords(((MainActivity)getActivity()).cardNo, orderAmount.intValue(), orderAmount.intValue(), 0);
                break;
            case R.id.layout_card:
                if(isReadingCard) {
                    stopTimer();
                }else {
                    startTimer();
                }
                break;
        }
    }

    class ClockThread extends Thread {
        @Override
        public void run() {
            do {
                try {
                    Thread.sleep(1000);
                    Message msg = new Message();
                    msg.what = 1;  //消息(一个整型值)
                    clockHandler.sendMessage(msg);// 每隔1秒发送一个msg给clockHandler
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } while (true);
        }
    }

    //【时钟的】 在主线程里面处理消息并更新UI界面
    private Handler clockHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    long sysTime = System.currentTimeMillis();//获取系统时间
                    CharSequence sysTimeStr = DateFormat.format("yyyy年MM月dd日 HH:mm:ss", sysTime);//时间显示格式
                    time.setText(sysTimeStr); //更新时间
                    break;
                default:
                    break;

            }
        }
    };

    //【读卡的】 在主线程里面处理消息并更新UI界面
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    LogUtil.i("---mHandler:cardNo=" + ((MainActivity)getActivity()).cardNo);
                    if (textWatcher !=null){
                        editCard.removeTextChangedListener(textWatcher);
                    }
                    String card = (String)msg.obj;
                    if(TextUtils.isEmpty(card)) {
                        clearCardInfo();
                        ((MainActivity)getActivity()).notifyUserScreenCardInfo(null);
                    }
                    editCard.setText(card);
                    editCard.addTextChangedListener(textWatcher);
                    editCard.requestFocus();
                    break;
                case 100:
                    textReadStatus.setText("读卡中...");
                    break;
                case 101:
                    textReadStatus.setText("轻触读卡");
                    break;
                default:
                    break;

            }
        }
    };

    private void startTimer(){
        if(isReadingCard)return;
        isReadingCard = true;
        mHandler.sendEmptyMessage(100);
        //二维码读码开启
        editCard.postDelayed(new Runnable() {
            @Override
            public void run() {
                editCard.requestFocus();
            }
        }, 500);
        //读卡器开启
        if (mTimer == null) {
            mTimer = new Timer();
        }
        if (mTimerTask == null) {
            mTimerTask = new TimerTask() {
                @Override
                public void run() {
                    LogUtil.i("---timer scan card times: " + count);
                    //String sn = NFCController.getM1Sn(call_contactLess, NFCController.PT_USB,"/dev/ttyS4", 115200);
                    String sn = getCard();
                    LogUtil.i("---timer scan card result1: " + sn);
                    if(!TextUtils.isEmpty(sn)) {
                        if(sn.length() >= 8) {
                            sn = sn.substring(0, 8);
                            LogUtil.i("---timer scan card result2: " + sn);
                            if (!sn.equals(((MainActivity)getActivity()).cardNo)) {
                                ((MainActivity)getActivity()).cardNo = sn;
                                fetchCardInfo(((MainActivity)getActivity()).cardNo);
                            }
                        }else {
                            ((MainActivity)getActivity()).cardNo = "";
                        }
                        Message msg = new Message();
                        msg.what = 1;
                        msg.obj = ((MainActivity)getActivity()).cardNo;
                        mHandler.sendMessage(msg);
                    }else {
                        ((MainActivity)getActivity()).cardNo = "";
                    }
                    do {
                        try {
                            Thread.sleep(3*period);
                        } catch (InterruptedException e) {
                        }
                    } while (isPause);
                    count ++;
                }
            };
        }
        if(mTimer != null && mTimerTask != null ) {
            mTimer.schedule(mTimerTask, 1000, period);
        }
    }

    private String getCard() {
        //连接端口成功
        if (hdev != -1) {
            result = call_contactLess.fw_getver(hdev, pModVer);
            if(0 == result) {
                //获取卡号 UID
                result = call_contactLess.fw_card_str(hdev, (short)1, pSnrM1);
                if(0 == result) {
                    return String.valueOf(pSnrM1);
                }
            }
        }
        return "No Card";
    }

    private void stopTimer(){
        isReadingCard = false;
        mHandler.sendEmptyMessage(101);
        //二维码读码关闭
        editCard.postDelayed(new Runnable() {
            @Override
            public void run() {
                editCard.clearFocus();
            }
        }, 500);
        //读卡器关闭
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }
        count = 0;
    }

    private void fetchCardInfo(String cardNo) {
        stopTimer();
        soundpool.play(soundMap.get(0), 1, 1, 0, 0, 1);
        HashMap<String, String> params = new HashMap<>();
        params.put("posSn", BaseApplication.getInstance().getWinId());
        params.put("cardNo", cardNo);
        HttpUtil.getInstance().get(BaseApplication.getInstance().getBaseUrl() + Constants.url_checkCard, params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject response) {
                LogUtil.e("response==" + response.toString());
                int code = response.optInt("ret");
                if(code == 0) {
                    cardInfo = gson.fromJson(response.optString("consumeUser"), CardInfo.class);
                    fillCardInfo(cardInfo);
                }else {
                    showDialog(response.optString("msg"), 2000);
                    ((MainActivity)getActivity()).notifyUserScreenDialog(response.optString("msg"), 2000);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                StatusUtils.handleError(ex, getActivity());
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
                startTimer();
            }
        });
    }

    private void reportConsumeRecords(final String cardNo, int orderAmount, int actualAmount, int discountAmount) {
        HashMap<String, String> params = new HashMap<>();
        params.put("posSn", BaseApplication.getInstance().getWinId());
        params.put("merchantNo", BaseApplication.getInstance().getWinId());
        params.put("windowNo", BaseApplication.getInstance().getWinId());
        params.put("cardNo", cardNo);
        params.put("flowId", String.valueOf(BaseApplication.getInstance().getFlowId()));
        params.put("orderAmount", String.valueOf(orderAmount));
        params.put("actualAmount", String.valueOf(actualAmount));
        params.put("discountAmount", String.valueOf(discountAmount));
        HttpUtil.getInstance().get(BaseApplication.getInstance().getBaseUrl() + Constants.url_reportConsumeRecords, params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject response) {
                LogUtil.e("response==" + response.toString());
                showDialog(response.optString("msg"), 2000);
                ((MainActivity)getActivity()).notifyUserScreenDialog(response.optString("msg"), 2000);
                if(BaseApplication.getInstance().getPriceType() == PriceType.Input) {
                    editMoney.setText("");//清空用于显示交易金额的文本
                    keyboard.clear();//清空自定义键盘缓存的数字
                }
                int code = response.optInt("code");
                if(code == 0) {
                    soundpool.play(soundMap.get(1), 1, 1, 0, 0, 1);
                }else if(code == 10003) {
                    soundpool.play(soundMap.get(2), 1, 1, 0, 0, 1);
                }else if(code == 10008) {
                    soundpool.play(soundMap.get(3), 1, 1, 0, 0, 1);
                }else if(code == 10009) {
                    soundpool.play(soundMap.get(4), 1, 1, 0, 0, 1);
                }else {
                    soundpool.play(soundMap.get(5), 1, 1, 0, 0, 1);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
            }
        });
    }

    private void clearCardInfo() {
        textName.setText("姓名：");
        editCard.setText("");
        textYue.setText("余额：");
    }

    private void fillCardInfo(CardInfo cardInfo) {
        ((MainActivity)getActivity()).notifyUserScreenCardInfo(cardInfo);
        if(cardInfo != null) {
            String cardStatus = "";
            switch (cardInfo.getCARDSTATUS()) {
                case -1:
                    cardStatus = "未发卡";
                    break;
                case 0:
                    cardStatus = "停用";
                    break;
                case 1:
                    cardStatus = "正常";
                    break;
                case 2:
                    cardStatus = "解挂";
                    break;
                case 3:
                    cardStatus = "挂失";
                    break;
                case 4:
                    cardStatus = "换卡";
                    break;

            }
            //cardStatusText.setText(cardStatus);
            textName.setText("姓名：" + cardInfo.getUSERNAME() + " [卡状态：" + cardStatus + "]");
            textYue.setText("余额：" + cardInfo.getACCOUNTBALANCE().toString());
            if(cardInfo.getCARDSTATUS() == 1 && BaseApplication.getInstance().getPriceType() == PriceType.Auto) {
                BigDecimal autoPrice = new BigDecimal(BaseApplication.getInstance().getAutoPrice());
                BigDecimal p = new BigDecimal(100);
                BigDecimal orderAmount = autoPrice.multiply(p);
                reportConsumeRecords(((MainActivity)getActivity()).cardNo, orderAmount.intValue(), orderAmount.intValue(), 0);
            }
        }else {
            clearCardInfo();
        }
    }
}

